package com.test.study;

import com.test.study.pojo.GpRpcReq;
import com.test.study.pojo.GpRpcResp;

import com.test.study.protocol.GpReqDecoder;
import com.test.study.protocol.GpRespEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * @ClassName NettyTransport
 * @Description TODO
 * @Author USER
 * @Date 2019/7/13 10:17
 * @Company
 **/
public class NettyTransport extends ChannelInboundHandlerAdapter {

    private String host;
    private int port;

    private Object result;

    public NettyTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.result = msg;
        GpRpcResp resp = (GpRpcResp) msg;
        System.out.println("收到服务端的请求响应："+resp.getMsg());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常："+cause.getMessage());
        ctx.close();
    }

    public Object send(GpRpcReq req){
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
//                        pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE,
//                                ClassResolvers.cacheDisabled(null)));
//                        pipeline.addLast(new ObjectEncoder());
                        pipeline.addLast(new GpReqDecoder(GpRpcResp.class));
                        pipeline.addLast(new GpRespEncoder(GpRpcReq.class));
                        pipeline.addLast(NettyTransport.this);
                    }
                }).option(ChannelOption.TCP_NODELAY,true);

        try {
            // 发送远程请求
            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().writeAndFlush(req).sync();
            if(req!=null){
                future.channel().closeFuture().sync();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            eventExecutors.shutdownGracefully();
        }
        return result;

    }

}
